package eu.jk.web.servlet;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.jk.base.security.AuthFilter;
import eu.jk.web.io.download.DownloadInfo;
import eu.jk.web.io.download.DownloadInfoManager;


public class DownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public DownloadServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		DownloadInfo fi = DownloadInfoManager.getDownloadInfo(request.getParameter("key"));
		String filename = fi.getFilename();
		File file = new File(fi.getRealPath());
		String browser=request.getHeader("user-agent");
		RandomAccessFile rf = new RandomAccessFile(file,"r");
		// 设置响应头
		int http_status=206;
		if(browser.contains("MSIE"))
			http_status=200;//200 响应头，不支持断点续传
		response.reset();
		response.setStatus(http_status);
		response.setContentType("application/octet-stream;charset=UTF-8");
		try {
			long since=0;
			long until=file.length()-1;
			String range=request.getHeader("range");//获取Range
			if(range!=null){
				//分解range
				range=range.split("=")[1];
				String[] rs=range.split("-");
				if(AuthFilter.isDigit(rs[0])){
					since=Integer.parseInt(rs[0]);
				}
				if(rs.length>1&&AuthFilter.isDigit(rs[1])){
					until=Integer.parseInt(rs[1]);
				}
			}
			response.setHeader("Accept-Ranges", "bytes");
			response.setHeader("Content-Range", "bytes "+since+"-"+ until + "/"
					+ file.length());
			response.setHeader("Content-Disposition", "attachment; filename=\"" +
					new String(filename.getBytes(),"ISO8859_1")+ "\"");
			response.setHeader("Content-Length", "" + (until-since+1));
			System.out.println("download: "+filename);
			//定位到请求位置
			rf.seek(since);
			byte[] buffer=new byte[128*1024];
			int len;
			boolean full=false;
			while((len=rf.read(buffer))>0){
				if(rf.getFilePointer()-1>until){
					len=(int) (len-(rf.getFilePointer()-until-1));
					full=true;
				}
				response.getOutputStream().write(buffer, 0, len);
				if(full)
					break;
			}
			//输出
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (java.net.SocketException e) {
			
		}finally{
			if(rf!=null)
				rf.close();
		}
		response.flushBuffer();
	}

	public void init() throws ServletException {
		// Put your code here
	}
}
